local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
module(...)
_VERSION = '0.1'


function send(args)
    local smtp = require("smtp")
    local json = require "cjson"
    
    local from = "<ericzhang0415@163.com>"
    local rcpt = "<51324842@qq.com>"
    local mesgt = {
        headers = {
            to = "51324842@qq.com",
            subject = "测试主题",
        },
        body = "这里是主题"
    }
    -- mesgt.headers["content-type"] = 'text/html; charset="utf-8"'

    local mailt = {
        server = "smtp.163.com",
        user = "ericzhang0415@163.com",
        password = "EyEsonmE27",
        from = from,
        rcpt = rcpt,
    --  source = smtp:message(mesgt)
        mesgt = mesgt
    }

    local s = smtp:new(mailt.server, mailt.port, mailt.create)

    local ext = s:greet(mailt.domain)
    ngx.log(ngx.ERR, ext)
    local auth, reply = s:auth(mailt.user, mailt.password, ext)
    ngx.log(ngx.ERR, auth)
    ngx.log(ngx.ERR, reply)
    local code, reply = s:send(mailt)
    ngx.log(ngx.ERR, code)
    ngx.log(ngx.ERR, reply)
    -- s:quit()
    -- s:close()

    if not code then
        ngx.print(json.encode({
            err = 0,
            msg = "mail send error " .. json.encode(reply)
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = reply
        }))
        ngx.exit(200)
    end
end

function default(args)
    local conf = require "conf"
    -- local uid, aid = conf.parse_token(args.token, "role")
    -- conf.check_permissions(uid, "role")
    if args.action == 'send' then
        send(args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
